import 'dart:convert';
import 'dart:math';

import 'package:get/get.dart';
import 'package:tiktokadult/hj_model/home/collection_resp.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_utils/light_model.dart';

import '../hj_model/cartoon_media_info.dart';

/// 针对项目来调整
enum HistoryRecordType {
  video, //长视频
  short, //短视频
  comics, //漫画
  cartoon, //卡通
  novel, //小说
  post, //帖子
  picture, //图集
  game, //黄游
}

const String acgSubMediaRecord = 'acgSubMediaRecord';

class HistoryRecordUtil {
  static const int maxLength = 50;
  static const String historySearchKey = 'HistorySearchKey'; //历史搜索

  static insertHistoryModel<T>(T model, HistoryRecordType type) async {
    if (model == null) return;
    try {
      final id = getModelId(model);
      final historys = await fetchHistory<T>(type);
      final cm = historys.firstWhereOrNull((element) => getModelId<T>(element) == id);
      if (cm != null) {
        historys.remove(cm);
        historys.insert(0, cm);
      } else {
        historys.insert(0, model);
      }
      final temp = historys.map((e) {
        final json = historyModelToJsonString<T>(e);
        return jsonEncode(json);
      }).toList();
      await lightKV.setStringList(type.toString(), temp.sublist(0, min(maxLength, temp.length)));
    } catch (e) {
      print('insertHistoryModel $e');
    }
  }

  static deleteHistoryModel<T>(T model, HistoryRecordType type) async {
    if (model == null) return;
    try {
      final id = getModelId(model);
      final historys = await fetchHistory<T>(type);
      final cm = historys.firstWhereOrNull((element) => getModelId<T>(element) == id);
      if (cm != null) {
        historys.remove(cm);
      }
      final temp = historys.map((e) {
        final json = historyModelToJsonString<T>(e);
        return jsonEncode(json);
      }).toList();
      await lightKV.setStringList(type.toString(), temp.sublist(0, min(maxLength, temp.length)));
    } catch (e) {
      print('insertHistoryModel $e');
    }
  }

  static deleteAll(HistoryRecordType type) async {
    try {
      await lightKV.setStringList(type.toString(), []);
    } catch (e) {
      print('insertHistoryModel $e');
    }
  }

  static Map<String, dynamic> historyModelToJsonString<T>(T model) {
    switch (T) {
      case VideoModel:
        return (model as VideoModel).toJson();
      case CartoonMediaInfo:
        return (model as CartoonMediaInfo).toJson();
      case CollectionModel:
        return (model as CollectionModel).toJson();
      default:
        return (model as VideoModel).toJson();
    }
  }

  static T? historyJsonStrToModel<T>(String jsons) {
    final json = Map<String, dynamic>.from(jsonDecode(jsons));
    switch (T) {
      case VideoModel:
        return VideoModel.fromJson(json) as T;
      case CartoonMediaInfo:
        return CartoonMediaInfo.fromJson(json) as T;
      case CollectionModel:
        return CollectionModel.fromJson(json) as T;
      default:
        return VideoModel.fromJson(json) as T;
    }
  }

  static String? getModelId<T>(T model) {
    switch (T) {
      case VideoModel:
        return (model as VideoModel).id;
      case CartoonMediaInfo:
        return (model as CartoonMediaInfo).id;
      case CollectionModel:
        return (model as CollectionModel).id;
      default:
        return null;
    }
  }

  static Future<List<T>> fetchHistory<T>(HistoryRecordType type) async {
    try {
      final history = await lightKV.getStringList(type.toString());
      if (history?.isEmpty ?? true) return <T>[];
      return List<T>.from(history!.map((e) {
        return historyJsonStrToModel<T>(e);
      }).toList());
    } catch (e) {
      print('fetchHistorys $e');
      return <T>[];
    }
  }

  /// 插入acg 相关播放集数
  static insertACGRecord(CartoonMediaInfo? info, {int index = 0}) async {
    if (info == null) {
      return;
    }
    var records = await _fetchTotalACGRecord();
    records ??= {};
    records[info.id] = index;
    lightKV.setString(acgSubMediaRecord, json.encode(records));
  }

  static Future<int> fetcACGRecord(CartoonMediaInfo? info) async {
    if (info == null) return 0;
    var records = await _fetchTotalACGRecord();
    return records?[info.id] ?? 0;
  }

  /// 获取acg 相关播放集数
  static Future<Map?> _fetchTotalACGRecord() async {
    final res = await lightKV.getString(acgSubMediaRecord);
    if (res?.isEmpty ?? true) return null;
    try {
      final records = Map.from(json.decode(res!));
      return records;
    } catch (e) {
      return null;
    }
  }

  //获取搜索历史记录
  static Future<List<String>> getSearchHistorys() async {
    return (await lightKV.getStringList(historySearchKey)) ?? <String>[];
  }

  //保存搜索历史
  static saveSearch(List<String> list) async {
    await lightKV.setStringList(historySearchKey, list);
  }
}
